package com.pll.service.Impl;

import com.pll.constant.ConstantField;
import com.pll.controller.admin.user.vo.MerchantLoginVO;
import com.pll.controller.admin.user.vo.MerchantRegistrationVO;
import com.pll.controller.admin.user.vo.MerchantSettledVO;
import com.pll.dto.ResponseDto;
import com.pll.mapper.UserMapper;
import com.pll.pojo.Merchant;
import com.pll.service.UserService;
import com.pll.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @className: UserServiceImpl
 * @author: XR_Z
 * @date: 2025/6/7 18:22
 * @Version: 1.0
 * @description: 用户ServiceImpl
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    ResponseDto dto = null;

    @Override
    public ResponseDto login(MerchantLoginVO loginVO, HttpServletRequest request) {
        HashMap<String, Object> merchant_jwt = new HashMap<>();
        dto = ResponseDto.fail(-1,"验证码错误~");
        //如果验证码相等，进行下一步操作
        if (loginVO.getCaptcha().equalsIgnoreCase(String.valueOf(redisTemplate.opsForValue().get(ConstantField.MerchantsKey.CAPTCHA_VALUE+request.getSession().getId())))) {
            Merchant merchant = userMapper.login(loginVO);
            if (merchant != null){
                // 生成token，然后存入redis中
                HashMap<String, Object> map = new HashMap<>();
                map.put("acc", loginVO.getAccount());
                String jwt = JwtUtils.generateJwt(map);

                redisTemplate.opsForValue().set(jwt, merchant, 3600, TimeUnit.SECONDS); //向redis中添加集合，并设置1小时后删除

                merchant_jwt.put("jwt", jwt);
                merchant_jwt.put("merchant", merchant);

                dto = ResponseDto.success(merchant_jwt);
            }else
                dto = ResponseDto.err(-1,"账号或密码错误~");
        }
        //删除redis中的验证码--》防止重复使用
        redisTemplate.delete(ConstantField.MerchantsKey.CAPTCHA_VALUE+request.getSession().getId());
        return dto;
    }

    @Override
    public ResponseDto enroll(MerchantRegistrationVO merchantRegistrationVO) {
        if (userMapper.MerchantIsExist(merchantRegistrationVO)==null){
            if (userMapper.enroll(merchantRegistrationVO) > 0){
                return ResponseDto.success("注册成功");
            }
        }
        return ResponseDto.fail(405,"注册失败,账号已存在");
    }

    @Override
    public ResponseDto merchantSettled(MerchantSettledVO merchantSettledVO) {
        dto = ResponseDto.err(405,"入驻失败~请稍后重试！");
        if (userMapper.merchantSettled(merchantSettledVO) > 0){
            dto = ResponseDto.success("入驻成功~");
        }

        return dto;
    }
}
